<?php

namespace app\index\service;

use app\common\model\ConsultingMessage;
use app\index\service\wrappers\MessageWrapperInterface;
use ShidianUtil\Utils\ArrayUtil;
use think\Collection;

/**
 * Class MessageContentService
 * @package app\consulting\service
 */
class MessageContentService
{
    /**
     * 包装动态消息
     * @param ConsultingMessage $message
     * @return void
     */
    public function wrapDynamicMessage(ConsultingMessage $message)
    {
        // 消息类型 text纯文本 post富文本 image图片 audio音频 media视频 file文件 server咨询服务推荐 lawyer 律师名片 system 系统消息 comment评价
        $wrapper = $this->getWrapper($message->messageType);
        if ($wrapper) {
            $wrapper->wrapMessage($message);
        }
    }

    /**
     * 批量包装动态消息
     * @param Collection $messages
     * @return void
     */
    public function wrapDynamicMessages(Collection $messages)
    {
        $collections = ArrayUtil::groups($messages->all(), function ($message) {
            return $message->messageType;
        });
        foreach ($collections as $messageType => $arr) {
            $wrapper = $this->getWrapper($messageType);
            if ($wrapper) {
                $wrapper->wrapMessages($arr);
            }
        }
    }

    private function getWrapper($messageType): ?MessageWrapperInterface
    {
        return app_instance(MessageWrapperInterface::class, $messageType, '', 'MessageWrapper');
    }
}
